package com.ecommerce.service;

import com.ecommerce.entity.Order;
import com.ecommerce.entity.OrderItem;
import com.ecommerce.repository.OrderRepository;
import com.ecommerce.repository.OrderItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class OrderService {

    @Autowired
    private OrderRepository orderRepository;
    
    @Autowired
    private OrderItemRepository orderItemRepository;

    // 获取用户订单列表
    public Map<String, Object> getUserOrders(Long userId, int page, int size, String status) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            PageRequest pageRequest = PageRequest.of(page, size);
            Page<Order> orderPage;
            
            if (status != null && !status.isEmpty()) {
                Order.OrderStatus orderStatus = Order.OrderStatus.valueOf(status.toUpperCase());
                orderPage = orderRepository.findByUserIdAndStatusOrderByCreatedAtDesc(userId, orderStatus, pageRequest);
            } else {
                orderPage = orderRepository.findByUserIdOrderByCreatedAtDesc(userId, pageRequest);
            }
            
            response.put("success", true);
            response.put("orders", orderPage.getContent());
            response.put("totalElements", orderPage.getTotalElements());
            response.put("totalPages", orderPage.getTotalPages());
            response.put("currentPage", page);
            response.put("size", size);
            return response;
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取订单列表失败: " + e.getMessage());
            return response;
        }
    }

    // 获取订单详情
    public Map<String, Object> getOrderDetail(Long userId, Long orderId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Optional<Order> order = orderRepository.findById(orderId);
            if (order.isPresent() && order.get().getUserId().equals(userId)) {
                // 获取订单商品
                List<OrderItem> orderItems = orderItemRepository.findByOrderId(orderId);
                
                // 手动设置订单商品列表
                Order orderEntity = order.get();
                orderEntity.setOrderItems(orderItems);
                
                response.put("success", true);
                response.put("order", orderEntity);
                response.put("orderItems", orderItems);
                return response;
            } else {
                response.put("success", false);
                response.put("message", "订单不存在");
                return response;
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取订单详情失败: " + e.getMessage());
            return response;
        }
    }

    // 创建订单
    @Transactional
    public Map<String, Object> createOrder(Long userId, Map<String, Object> orderData) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Order order = new Order();
            order.setUserId(userId);
            order.setOrderNumber(generateOrderNumber());
            order.setStatus(Order.OrderStatus.PENDING);
            order.setTotalAmount(new BigDecimal(orderData.get("totalAmount").toString()));
            order.setReceiverName(orderData.get("receiverName").toString());
            order.setReceiverPhone(orderData.get("receiverPhone").toString());
            order.setReceiverAddress(orderData.get("receiverAddress").toString());
            order.setPaymentMethod(Order.PaymentMethod.valueOf(orderData.get("paymentMethod").toString()));
            order.setPaymentStatus(Order.PaymentStatus.UNPAID);
            order.setRemark(orderData.get("remark") != null ? orderData.get("remark").toString() : "");
            
            Order savedOrder = orderRepository.save(order);
            
            // 保存订单商品
            List<Map<String, Object>> items = (List<Map<String, Object>>) orderData.get("items");
            for (Map<String, Object> item : items) {
                OrderItem orderItem = new OrderItem();
                orderItem.setOrder(savedOrder);
                orderItem.setProductId(Long.valueOf(item.get("productId").toString()));
                orderItem.setProductName(item.get("productName").toString());
                orderItem.setProductImage(item.get("productImage") != null ? item.get("productImage").toString() : "");
                orderItem.setPrice(new BigDecimal(item.get("price").toString()));
                orderItem.setQuantity(Integer.valueOf(item.get("quantity").toString()));
                orderItem.setSubtotal(new BigDecimal(item.get("subtotal").toString()));
                
                orderItemRepository.save(orderItem);
            }
            
            response.put("success", true);
            response.put("order", savedOrder);
            response.put("message", "订单创建成功");
            return response;
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "创建订单失败: " + e.getMessage());
            return response;
        }
    }

    // 取消订单
    @Transactional
    public Map<String, Object> cancelOrder(Long userId, Long orderId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Optional<Order> order = orderRepository.findById(orderId);
            if (order.isPresent() && order.get().getUserId().equals(userId)) {
                Order orderEntity = order.get();
                if (orderEntity.getStatus() == Order.OrderStatus.PENDING) {
                    orderEntity.setStatus(Order.OrderStatus.CANCELLED);
                    orderRepository.save(orderEntity);
                    
                    response.put("success", true);
                    response.put("message", "订单取消成功");
                    return response;
                } else {
                    response.put("success", false);
                    response.put("message", "订单状态不允许取消");
                    return response;
                }
            } else {
                response.put("success", false);
                response.put("message", "订单不存在");
                return response;
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "取消订单失败: " + e.getMessage());
            return response;
        }
    }

    // 生成订单号
    private String generateOrderNumber() {
        LocalDateTime now = LocalDateTime.now(); // 获取当前时间
        String timestamp = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")); // 格式化时间戳
        String random = String.valueOf((int)(Math.random() * 1000)); // 生成随机数
        return "ORDER" + timestamp + random; // 返回订单号
    }
    
    // 根据购物车创建订单（用于支付功能）
    @Transactional // 事务注解，确保数据一致性
    public Map<String, Object> createOrderFromCart(Long userId, Map<String, Object> orderData) {
        Map<String, Object> response = new HashMap<>(); // 创建响应对象
        
        try {
            // 创建订单对象
            Order order = new Order(); // 创建新订单
            order.setUserId(userId); // 设置用户ID
            order.setOrderNumber(generateOrderNumber()); // 生成订单号
            order.setStatus(Order.OrderStatus.PENDING); // 设置订单状态为待付款
            order.setTotalAmount(new BigDecimal(orderData.get("totalAmount").toString())); // 设置总金额
            order.setReceiverName(orderData.get("receiverName").toString()); // 设置收货人姓名
            order.setReceiverPhone(orderData.get("receiverPhone").toString()); // 设置收货人电话
            order.setReceiverAddress(orderData.get("receiverAddress").toString()); // 设置收货地址
            order.setPaymentMethod(Order.PaymentMethod.valueOf(orderData.get("paymentMethod").toString())); // 设置支付方式
            order.setPaymentStatus(Order.PaymentStatus.UNPAID); // 设置支付状态为未支付
            order.setRemark(orderData.get("remark") != null ? orderData.get("remark").toString() : ""); // 设置备注
            
            // 保存订单
            Order savedOrder = orderRepository.save(order); // 保存订单到数据库
            
            // 处理购物车商品（如果有的话）
            if (orderData.containsKey("items") && orderData.get("items") instanceof List) {
                List<Map<String, Object>> items = (List<Map<String, Object>>) orderData.get("items"); // 获取商品列表
                for (Map<String, Object> item : items) { // 遍历商品列表
                    OrderItem orderItem = new OrderItem(); // 创建订单项
                    orderItem.setOrder(savedOrder); // 设置订单
                    orderItem.setProductId(Long.valueOf(item.get("productId").toString())); // 设置商品ID
                    orderItem.setProductName(item.get("productName").toString()); // 设置商品名称
                    orderItem.setProductImage(item.get("productImage") != null ? item.get("productImage").toString() : ""); // 设置商品图片
                    orderItem.setPrice(new BigDecimal(item.get("price").toString())); // 设置商品价格
                    orderItem.setQuantity(Integer.valueOf(item.get("quantity").toString())); // 设置商品数量
                    orderItem.setSubtotal(new BigDecimal(item.get("price").toString()).multiply(new BigDecimal(item.get("quantity").toString()))); // 设置小计
                    
                    orderItemRepository.save(orderItem); // 保存订单项
                }
            }
            
            response.put("success", true); // 设置成功状态为true
            response.put("message", "订单创建成功"); // 设置成功消息
            response.put("order", savedOrder); // 返回创建的订单
            return response; // 返回响应
            
        } catch (Exception e) { // 捕获异常
            response.put("success", false); // 设置成功状态为false
            response.put("message", "创建订单失败: " + e.getMessage()); // 设置错误消息
            return response; // 返回响应
        }
    }
}